import { routerRedux } from 'dva/router';
import app from '../app';
import { getRoute } from '../config/route';

export function searchParams(searchStr) {
  if (!searchStr) return {};

  const search = searchStr[0] === '?' ? searchStr.substr(1) : searchStr;

  return search.split('&').reduce((acc, item) => {
    const [key, val] = item.split('=');
    if (!key) {
      return acc;
    }

    let target = acc[key];

    if (target) {
      if (Array.isArray(target)) {
        target.push(val);
      } else {
        target = [target, val];
      }
    } else {
      target = val;
    }

    return { ...acc, [`${key}`]: target };
  }, {});
}

export function flattenError(errors) {
  return Object.keys(errors).map(k => errors[k].errors[0]);
}

export function redirect(to) {
  app._store.dispatch(routerRedux.push(getRoute(to))); // eslint-disable-line
}
